/*
  Copyright 2012 Sergey Ostanin

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

package ru.irenproject;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;

import ru.irenproject.store.Ids;

import com.google.common.io.Closeables;
import com.google.protobuf.ByteString;

public final class Request implements AutoCloseable {
  private Reader fReader;
  private BufferedReader fBufferedReader;
  private final ByteString fChannelId;
  private final ByteString fTargetId;
  private final String fActionName;

  public Request(byte[] data) {
    boolean ok = false;
    try {
      fReader = new InputStreamReader(new ByteArrayInputStream(data), StandardCharsets.UTF_8);
      fBufferedReader = new BufferedReader(fReader);

      fChannelId = Ids.fromAlienHexString(fBufferedReader.readLine());
      fTargetId = Ids.fromAlienHexString(fBufferedReader.readLine());
      fActionName = Check.inputNotNull(fBufferedReader.readLine());

      ok = true;
    } catch (IOException e) {
      throw new RuntimeException(e);
    } finally {
      if (!ok) {
        close();
      }
    }
  }

  @Override public void close() {
    if (fBufferedReader != null) {
      Closeables.closeQuietly(fBufferedReader);
      fBufferedReader = null;
    }

    if (fReader != null) {
      Closeables.closeQuietly(fReader);
      fReader = null;
    }
  }

  public BufferedReader contentReader() {
    return fBufferedReader;
  }

  public ByteString channelId() {
    return fChannelId;
  }

  public ByteString targetId() {
    return fTargetId;
  }

  public String actionName() {
    return fActionName;
  }
}
